package com.atxwq.shop.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.atxwq.shop.common.exception.GlobalException;
import com.atxwq.shop.model.dto.h5.UserLoginDto;
import com.atxwq.shop.model.dto.h5.UserRegisterDto;
import com.atxwq.shop.model.entity.user.UserInfo;
import com.atxwq.shop.model.vo.common.RedisCodeEnum;
import com.atxwq.shop.model.vo.common.ResultCodeEnum;
import com.atxwq.shop.model.vo.h5.UserInfoVo;
import com.atxwq.shop.user.mapper.UserInfoMapper;
import com.atxwq.shop.user.service.UserInfoService;
import com.atxwq.utils.AuthContextUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO
 * @Date 2025/5/22 13:19
 * @Created by 12336
 */

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //1.从Dto中获取数据 (密码，手机号，验证码，昵称)
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();

        //校验参数
        if(StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(nickName) ||
                StringUtils.isEmpty(code)) {
            throw new GlobalException(ResultCodeEnum.DATA_ERROR);
        }

        //2.验证码校验 2.1 从Redis中获取验证码 2.2 获取输入验证码 2.3 比较
        //通过用户名去获得redis中的验证码
        String codeValueRedis = redisTemplate.opsForValue().get(username);
        if(!code.equals(codeValueRedis)){
            throw new GlobalException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //3.校验用户名是否重复
        UserInfo userInfo = userInfoMapper.getByUserName(username);
        if(userInfo != null){
            throw new GlobalException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //4.封装添加数据，调用方法添加数据库
        userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setNickName(nickName);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setPhone(username);
        userInfo.setStatus(1);
        userInfo.setSex(0);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");

        userInfoMapper.save(userInfo);

        //从redis中删除验证码
        redisTemplate.delete(username);

    }

    /**
     * 用户登录
     * @param userLoginDto
     * @return
     */
    @Override
    public String login(UserLoginDto userLoginDto) {
        //1.从Dto里获取数据 (用户名，密码)
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();
        //2.根据用户名查询数据库得到用户信息
        UserInfo userInfo = userInfoMapper.getByUserName(username);
        if(userInfo == null){
            throw new GlobalException(ResultCodeEnum.LOGIN_ERROR);
        }
        //3.校验密码
        String dataBasePassword = userInfo.getPassword();
        if(!DigestUtils.md5DigestAsHex(password.getBytes()).equals(dataBasePassword)){
            throw new GlobalException(ResultCodeEnum.LOGIN_ERROR);
        }
        //4.校验用户的状态：是否被禁用
        if(userInfo.getStatus() == 0){
            throw new GlobalException(ResultCodeEnum.ACCOUNT_STOP);
        }
        //5.生成token令牌
        String token = UUID.randomUUID().toString().replace("-","");

        //6.将token令牌存到redis中 30天方便测试
        String jsonString = JSON.toJSONString(userInfo);
        redisTemplate.opsForValue().set(RedisCodeEnum.USER_LOGIN_TOKEN + token, jsonString,30, TimeUnit.DAYS);

        //7.返回token
        return token;
    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
//        String userJson = redisTemplate.opsForValue().get(RedisCodeEnum.USER_LOGIN_TOKEN + token);
//        if(!StringUtils.hasText(userJson)){
//            throw new GlobalException(ResultCodeEnum.LOGIN_AUTH);
//        }
//        UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
        //从Threadlocal里获取用户信息
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo ;
    }
}
